package net.njcp.spi.compile;

import groovy.lang.GroovyClassLoader;
import net.njcp.spi.exception.SpiProxyCompileException;

/**
 * @ClassName GroovyCompile
 * @Description: 使用groovy动态执行java代码
 * @Author 柳拓
 * @Date 2019/8/6
 * @Version V1.0
 **/
public class GroovyCompile {

    /**
     *
     * @param code 动态代理类
     * @param interfaceType 接口类型
     * @param classLoader 类加载器
     * @param <T> 接口范型
     * @return
     * @throws SpiProxyCompileException
     */
    @SuppressWarnings("unchecked")
    public static <T> T compile(String code, Class<T> interfaceType, ClassLoader classLoader) throws SpiProxyCompileException {
        GroovyClassLoader loader = new GroovyClassLoader(classLoader);
        Class clz = loader.parseClass(code);

        if (!interfaceType.isAssignableFrom(clz)) {
            throw new IllegalStateException("illegal proxy type!");
        }


        try {
            return (T) clz.newInstance();
        } catch (Exception e) {
            throw new SpiProxyCompileException("init spiProxy error! msg: " + e.getMessage());
        }
    }

}
